window.addEventListener('DOMContentLoaded',init,true);
var $ = function(id) { return document.getElementById(id)};
var $F = function(id) { return $(id).value};
var Twit = {};

function init() {
    Twit.canvas=$('twits');
//    Twit.fetch();
    $('new_twit').addEventListener('keyup',Twit.count,true);
}
Twit.handleFetchEvent = function(e) {
    var image=e.target;//could be image, might not be
    Twit.fetch(image.twitter_name);
};
Twit.fetch = function(user) {
    user = user || $('user').value;
    var req = new XMLHttpRequest();
    var url = 'http://'+ 
	encodeURIComponent($F('email'))+':'+ 
	encodeURIComponent($F('pass'))+'@twitter.com/statuses/friends_timeline/'+user+'.json';
    req.open('GET',url);
    req.onreadystatechange = function (aEvt) {  
	if (req.readyState == 4) {  
	    if(req.status == 200)  {try{
		var x=eval(req.responseText);
	    } catch(err) { alert(req.responseText) }
		Twit.render(x);
	    }
	}
    };  
    req.send(null);
}
Twit.render = function(obj) {
    Twit.model=obj;
    var rows = Twit.canvas;
    while(rows.childNodes.length) rows.removeChild(rows.firstChild);
    var row;
    var labels = [];
    for(var i=0;i<obj.length;i++) {
	Twit.message(obj,i);
    }
}
Twit.message = function(obj,i) {
    var row = document.createElement('row');
    var label = document.createElement('label');
    var image = document.createElement('image');
    var text = document.createTextNode(obj[i].text);
    image.setAttribute('tooltiptext',obj[i].user.name);
    image.twitter_name = obj[i].user.screen_name;
    image.setAttribute('src',obj[i].user.profile_image_url);
    label.appendChild(text);
    row.appendChild(image);
    row.appendChild(label);
    Twit.canvas.appendChild(row);
}
Twit.toggleSettings = function() {
    var state = $('auth').getAttribute('class');
    state=(state=='hide')?'':'hide';
    $('auth').setAttribute('class',state);
}
Twit.new = function() {
    var url = 'http://'+
	encodeURIComponent($F('user'))+':'+
	encodeURIComponent($F('pass'))+'@'+
	'twitter.com/statuses/update.json';
    var req = new XMLHttpRequest();
    req.open('POST',url);
    req.setRequestHeader('Content-Type',
			     'application/x-www-form-urlencoded');
    req.onreadystatechange = function (aEvt) {  
	if (req.readyState == 4) {  
	    if(req.status == 200)  {
		Twit.fetch();
	    }
	}
    };  
    req.send('status='+encodeURIComponent($F('new_twit')));

}
Twit.count = function(e) {
    $('char_count').value=140-this.value.length;
}